package playscore;

import javax.swing.*;
import java.io.*;
import java.util.*;

class playerscore implements Comparable<playerscore> {
    String name;
    int score;

    public playerscore(String name, int score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public int compareTo(playerscore other) {
        return Integer.compare(other.score, this.score);
    }

    @Override
    public String toString() {
        return name + ": " + score;
    }
}

public class board {
    private java.util.List<playerscore> phboard = new java.util.ArrayList<>();

    public void loadboard() {
        try (BufferedReader reader = new BufferedReader(new FileReader("leaderboard.txt"))) {
            String line;
            while ((line = reader.readLine())!= null) {
                String[] parts = line.split(":");
                if (parts.length == 2) {
                    String name = parts[0];
                    int score = Integer.parseInt(parts[1].trim());
                    phboard.add(new playerscore(name, score));
                }
            }
        } catch (IOException e) {
            // 文件不存在或读取错误，使用空排行榜
        }
    }

    public void saveboard() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("leaderboard.txt"))) {
            for (playerscore playerScore : phboard) {
                writer.write(playerScore.name + ": " + playerScore.score);
                writer.newLine();
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "保存排行榜时出错: " + e.getMessage());
        }
    }

    public void updateboardArea(JTextArea leaderboardArea) {
        StringBuilder sb = new StringBuilder();
        Collections.sort(phboard);
        for (playerscore playerScore : phboard) {
            sb.append(playerScore).append("\n");
        }
        leaderboardArea.setText(sb.toString());
    }

    public void addPlayerScore(String playerName, int score) {
        phboard.add(new playerscore(playerName, score));
    }

 